package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.User;
import com.example.util.api.R;
import com.example.service.UserService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;

    @GetMapping("/list")
    public R list(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(user.getSno()), User::getSno, user.getSno());
        List<User> list = service.list(wrapper);
        return R.data(list);
    }

    @DeleteMapping("/delete")
    public R delete(@RequestParam("sno") String sno) {
        service.removeById(sno);
        return R.success("操作成功");
    }

    @PutMapping("/update")
    public R update(@RequestBody User user) {
        if (StrUtil.isBlank(user.getSno())) {
            return R.fail("请录入学号参数");
        }

        service.updateById(user);
        return R.success("操作成功");
    }

    @PostMapping("/save")
    public R save(@RequestBody User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getSno, user.getSno());
        if (service.count(wrapper) > 0) {
            return R.fail("学号重复");
        }
        service.save(user);
        return R.success("操作成功");
    }
}
